package com.yl.applicationsecurity.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yl.applicationsecurity.mapper.ApplicationCoverageInternetMapper;
import com.yl.applicationsecurity.mapper.ApplicationCoverageMapper;
import com.yl.applicationsecurity.mapper.ComponentUnauthorizedMapper;
import com.yl.applicationsecurity.pojo.ApplicationCoverage;
import com.yl.applicationsecurity.pojo.ApplicationCoverageInternet;
import com.yl.applicationsecurity.pojo.ComponentUnauthorized;
import com.yl.applicationsecurity.pojo.Inspection;
import com.yl.applicationsecurity.service.ApplicationCoverageService;
import com.yl.applicationsecurity.service.ComponentUnauthorizedService;
import com.yl.applicationsecurity.utils.AgentCheck;
import com.yl.applicationsecurity.utils.AppnameClientUtil;
import com.yl.applicationsecurity.utils.IASTClient;
import com.yl.applicationsecurity.utils.RASPClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author 鹤仙问鹿仙
 * @program: Application-security
 * @description:
 * @date 2025-01-26 10:12:04
 */
@Service
public class ApplicationCoverageServiceImpl  extends ServiceImpl<ApplicationCoverageMapper, ApplicationCoverage> implements ApplicationCoverageService {
    @Autowired
    private ApplicationCoverageInternetMapper applicationCoverageInternetMapper;

    @Override
    public PageInfo<ApplicationCoverage> findListByApplicationCoverage(ApplicationCoverage applicationCoverage, Integer pageNum, Integer pageSize) {

        PageHelper.startPage(pageNum, pageSize );//每页显示8条

        LambdaQueryWrapper<ApplicationCoverage> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        if ( StringUtils.isNotEmpty(applicationCoverage.getAppName())){
            lambdaQueryWrapper.like(ApplicationCoverage::getAppName,applicationCoverage.getAppName());
        }
        if ( applicationCoverage.getIsInternet()!=null){
            lambdaQueryWrapper.eq(ApplicationCoverage::getIsInternet,applicationCoverage.getIsInternet());
        }

        if ( applicationCoverage.getIastStatus()!=null){
            lambdaQueryWrapper.eq(ApplicationCoverage::getIastStatus,applicationCoverage.getIastStatus());
        }

        if ( applicationCoverage.getRaspStatus()!=null){
            lambdaQueryWrapper.eq(ApplicationCoverage::getRaspStatus,applicationCoverage.getRaspStatus());
        }

        if ( applicationCoverage.getLogicProbeStatus()!=null){
            lambdaQueryWrapper.eq(ApplicationCoverage::getLogicProbeStatus,applicationCoverage.getLogicProbeStatus());
        }
        lambdaQueryWrapper.orderByDesc(ApplicationCoverage::getAppName);
        List<ApplicationCoverage> list = baseMapper.selectList(lambdaQueryWrapper);



        PageInfo<ApplicationCoverage> pageInfo = new PageInfo<ApplicationCoverage>(list);
        if (pageInfo.getPages() == 0) {
            pageInfo.setPages(1);
        }

        return pageInfo;
    }

    @Override
    public Integer findApplicationCoverageCount(String type) {
        if(type.equals("IAST")){
            //IAST数量
        }else if (type.equals("RASP")){

        }else if (type.equals("ISINTERNET")){

        }else if (type.equals("LOGICPROBE")){

        }


        return null;
    }

    @Override
    public boolean getData() throws Exception {

        //获取当前UAT环境的所有应用
        List<ApplicationCoverage> UATAppNameList = AppnameClientUtil.getAppNameList();

        // 获取逻辑探针覆盖的所有应用
        List<String> agentList = AgentCheck.getAgentList();
        // 获取RASP覆盖的所有应用
        List<String> raspList = RASPClient.getData();
        // 获取IAST覆盖的所有应用
        List<String> iastList = IASTClient.getData();
        // 获取所有面向互联网的应用
        LambdaQueryWrapper<ApplicationCoverageInternet> applicationCoverageInternetLambdaQueryWrapper = new LambdaQueryWrapper<>();
        applicationCoverageInternetLambdaQueryWrapper.select(ApplicationCoverageInternet::getAppName); // 只查询id和name字段

        List<ApplicationCoverageInternet> isInternetListPojo  = applicationCoverageInternetMapper.selectList(applicationCoverageInternetLambdaQueryWrapper);

        // 手动提取 appName 字段
        List<String> isInternetList = isInternetListPojo.stream()
                .map(ApplicationCoverageInternet::getAppName)
                .collect(Collectors.toList());



        //删除所有数据
        LambdaQueryWrapper<ApplicationCoverage> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        baseMapper.delete(lambdaQueryWrapper);


        List<ApplicationCoverage> applicationCoverageList = new ArrayList<>();
        //更新或写入数据
        for (ApplicationCoverage applicationCoverage : UATAppNameList){
            applicationCoverage.setId(UUID.randomUUID().toString().replace("-",""));
            if(agentList.contains(applicationCoverage.getAppName())){
                applicationCoverage.setLogicProbeStatus(1);
            } else if (isInternetList.contains(applicationCoverage.getAppName())) {
                applicationCoverage.setLogicProbeStatus(0);
            } else{
                applicationCoverage.setLogicProbeStatus(2);
            }


            if(raspList.contains(applicationCoverage.getAppName())){
                applicationCoverage.setRaspStatus(1);
            }else{
                applicationCoverage.setRaspStatus(0);
            }

            if(iastList.contains(applicationCoverage.getAppName())){
                applicationCoverage.setIastStatus(1);
            }else{
                if (!applicationCoverage.getAppName().contains("yl")&&!applicationCoverage.getAppName().contains("jms")&&!applicationCoverage.getAppName().contains("sand")) {
                    applicationCoverage.setIastStatus(2);//无需覆盖
                } else{
                    applicationCoverage.setIastStatus(0);
                }
            }

            if(isInternetList.contains(applicationCoverage.getAppName())){
                applicationCoverage.setIsInternet(1);
            }else{
                applicationCoverage.setIsInternet(0);
            }

            applicationCoverageList.add(applicationCoverage);
            
        }


        for (ApplicationCoverage a:applicationCoverageList){
            baseMapper.insert(a);
        }
        return false;
    }

    @Override
    public  Map<String,Integer> getStatisticalDdata() {
        Map<String,Integer> map = new HashMap<String,Integer>();


        LambdaQueryWrapper<ApplicationCoverage> lambdaQueryWrapper = null;

        //获取IAST插桩数量
        lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ApplicationCoverage::getIastStatus,1);
        long iastCount = baseMapper.selectCount(lambdaQueryWrapper);
        map.put("iastCount",(int)iastCount);
        //获取IAST应插桩数量
        lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ne(ApplicationCoverage::getIastStatus,2);
        long iastAllCount = baseMapper.selectCount(lambdaQueryWrapper);
        map.put("iastAllCount",(int)iastAllCount);


        //获取RASP插桩数量
        lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ApplicationCoverage::getRaspStatus,1);
        long raspCount = baseMapper.selectCount(lambdaQueryWrapper);
        map.put("raspCount",(int)raspCount);
        //获取逻辑探针插桩数量
        lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ApplicationCoverage::getLogicProbeStatus,1);
        long logicProbeCount = baseMapper.selectCount(lambdaQueryWrapper);
        map.put("logicProbeCount",(int)logicProbeCount);
        //获取面向互联网应用插桩数量
        lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ApplicationCoverage::getIsInternet,1);
        long isInternetCount = baseMapper.selectCount(lambdaQueryWrapper);
        map.put("isInternetCount",(int)isInternetCount);
        //获取所有应用数量
        lambdaQueryWrapper = new LambdaQueryWrapper<>();
        long allCount = baseMapper.selectCount(lambdaQueryWrapper);
        map.put("allCount",(int)allCount);
        //获取面向互联网的应用中，逻辑探针覆盖的数量
        lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ApplicationCoverage::getIsInternet,1);
        lambdaQueryWrapper.eq(ApplicationCoverage::getLogicProbeStatus,1);
        long logicProbeIsInternetCount = baseMapper.selectCount(lambdaQueryWrapper);
        map.put("logicProbeIsInternetCount",(int)logicProbeIsInternetCount);

        //获取IAST应覆盖应用的数量


        return map;
    }

    @Override
    public ResponseEntity<ByteArrayResource> generateExcel() throws IOException {

            // 创建一个工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("Sample Sheet");

            // 创建表头
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("ID");
            headerRow.createCell(1).setCellValue("Name");
            headerRow.createCell(2).setCellValue("Age");

            // 添加数据
            Row row = sheet.createRow(1);
            row.createCell(0).setCellValue(1);
            row.createCell(1).setCellValue("John Doe");
            row.createCell(2).setCellValue(29);

            // 将工作簿写入到输出流中
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            workbook.close();

            // 将文件以字节数组形式返回
            ByteArrayResource resource = new ByteArrayResource(outputStream.toByteArray());

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=sample.xlsx")
                    .contentLength(resource.contentLength())
                    .body(resource);
        }


}

